<template>
    <el-form label-width="110px" size="small" class="form-row">
        <el-col :span="12">
            <el-form-item label="产品代码:">
                <RiskEntryInput id="fundCode" @set-entry-data="getFundCode" :returnDatas="orderForm.fundCode" />
            </el-form-item>
            <el-form-item label="资产单元编号:" v-if="SHOW_SECURITY">
                <el-select v-model="orderForm.assetCode" size="mini" @change="handleFormChange($event, 'assetCode')">
                    <el-option
                        v-for="i in computedAssetCodeSelectData"
                        :key="i.assetCode"
                        :label="i.assetCode + ' ' + i.assetName"
                        :value="i.assetCode"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="组合编码:">
                <el-select
                    name="fundAccountCode"
                    v-model="orderForm.fundAccountCode"
                    size="mini"
                    @change="handleFormChange($event, 'fundAccountCode')"
                >
                    <el-option
                        v-for="i in computedFundAccountCodeSelectData"
                        :key="i.fundAccountCode"
                        :label="i.fundAccountCode + ' ' + i.fundAccountName"
                        :value="i.fundAccountCode"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <div class="icon-form-item">
                <el-form-item label="证券代码:">
                    <el-select
                        name="stockCode"
                        size="mini"
                        clearable
                        filterable
                        :filter-method="queryStockCodeList"
                        v-model="orderForm.stockCode"
                        @change="handleFormChange($event, 'stockCode')"
                    >
                        <el-option
                            v-for="(i, index) in stockCodeSelectData"
                            :key="i.stockCode + index"
                            :label="i.stockCode + ' ' + i.stockName"
                            :value="i.stockCode"
                            @click.native="handleLabelClick(i.stockName)"
                            :name="'stockCode' + i.stockCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <i v-if="showIcon" class="el-icon-warning-outline" @click="stockDialog = true"></i>
            </div>

            <el-form-item label="业务类型:">
                <el-select name="businessType" v-model="orderForm.businessType" size="mini" disabled>
                    <el-option value="6" label="ETF一级市场业务"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="委托方向:" v-if="!SHOW_SECURITY">
                <el-select name="orderDirection" v-model="orderForm.orderDirection" size="mini" @change="handleFormChange($event, 'orderDirection')">
                    <el-option
                        v-for="i in orderDirectionSelectData"
                        :key="i.dictKey"
                        :label="i.dictKeyName"
                        :value="i.dictKey"
                        :name="'orderDirection' + i.dictKey"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="委托方向:" v-if="SHOW_SECURITY">
                <el-select name="orderDirection" v-model="orderForm.orderDirection" size="mini" @change="handleFormChange($event, 'orderDirection')">
                    <el-option
                        v-for="i in orderDirectionSelectData"
                        :key="i.dictKey"
                        :label="i.dictKeyName"
                        :value="i.dictKey"
                        :name="'orderDirection' + i.dictKey"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="投资类型:">
                <el-select name="investType" v-model="orderForm.investType" size="mini" disabled>
                    <el-option value="1" label="可交易"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="目标类型:">
                <el-select name="targetType" v-model="orderForm.targetType" size="mini" @change="handleFormChange($event, 'targetType')">
                    <el-option v-for="(value, key) in targetTypePojo" :key="key" :label="value" :value="key" :name="'targetType' + key"> </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="指令数量:">
                <RiskInputNumber
                    :disabled="orderForm.targetType == '2'"
                    :input="orderForm.orderAmount"
                    :inputAfter="'篮'"
                    :maxlength="14"
                    :field="'orderAmount'"
                    :precision="0"
                    @getInputNumber="getInputNumber(arguments)"
                >
                </RiskInputNumber>
            </el-form-item>

            <el-form-item label="指令金额:">
                <RiskInputNumber
                    :disabled="orderForm.targetType == '1'"
                    :input="orderForm.orderBalance"
                    :inputAfter="'万元'"
                    :precision="2"
                    :maxlength="14"
                    :field="'orderBalance'"
                    @getInputNumber="getInputNumber(arguments)"
                >
                </RiskInputNumber>
            </el-form-item>
        </el-col>
        <ConstituentStockDialog
            v-if="stockDialog"
            :showDialog="true"
            :stockDialog="stockDialog"
            :orderForm="orderForm"
            :etfBasicInfo="etfBasicInfo"
            @closeStockDialog="closeStockDialog"
        />
    </el-form>
</template>
<script lang="ts">
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { getConfigItem, handleTextColor, uniqueFunc } from '@/utils/tools';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import ConstituentStockDialog from '../etf-inst/constituentStock-dialog.vue';
import { getETFBasicInfo, getEtfList, getInstInfo } from '../api/etf';
import moment from 'moment';

/**
 * ETF指令表单组件
 */
@Component({
    name: 'ETFForm',
    components: {
        RiskInputNumber,
        RiskEntryInput,
        ConstituentStockDialog,
    },
})
export default class ETFForm extends Vue {
    @Prop() detail: any; // 指令表单回显数据
    @Prop() showIcon: boolean; // 成分股信息弹框点击图标，风险试算表单显示

    // 获取券商结算配置开关
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    // 指令表单
    orderForm: any = {
        fundCode: '', // 产品代码
        assetCode: '', // 资产单元编码
        assetName: '', // 资产单元名称
        fundAccountCode: '', // 组合编码
        orderDirection: 'P', // 委托方向
        stockCode: '', // 证券代码
        stockNameSt: '', // 证券名称
        reportCode: '', // 申报代码
        marketCode: '', // 交易市场编码
        businessType: '6', // 业务类型
        businClass: '6',
        orderPrice: '', // 指令价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 指令金额
        fundNameSt: '', // 产品简称
        fundAccountName: '', // 组合名称
        targetType: '1', // 目标类型
        investType: '1', // 投资类型
    };

    targetTypePojo: any = {}; // 目标类型枚举对象
    fundCodeSelectData: any[] = []; // 产品数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    stockCodeSelectData: any[] = []; // 证券代码下拉数据
    // 委托方向下拉数据
    orderDirectionSelectData: any[] = [
        { dictKey: 'P', dictKeyName: '基金申购' },
        { dictKey: 'Q', dictKeyName: '基金赎回' },
    ];
    stockDialog: boolean = false; // 成分股信息弹框显示

    // 计算指令数量\金额表单
    calcForm: any = {
        estimatecash: 0,
        execType: '',
        fundCode: '',
        instructionAmount: 0,
        instructionBalance: 0,
        orderDirection: '',
        paging: {
            currentPage: 0,
            pageSize: 0,
        },
        stockCode: '',
        stockTargetType: '',
    };
    etfBasicInfo: any = null; // 选中etf的基本信息

    async mounted() {
        // 获取目标类型
        this.targetTypePojo = DictionConstUtil.targetType;
        // 获取证券下拉代码
        this.queryStockCodeList('');
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like?fundCodeOrName=', '');
        // 获取组合编码下拉框数据
        let arr = await DictionConstUtil.FNFundAccount();
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
    }

    @Watch('renderCount', { immediate: true, deep: true })
    // 指令表单回显
    async setForm() {
        let instruction = this.detail;
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        this.handleStockCodeChange(instruction?.stockCode);
        for (const key in instruction) {
            this.orderForm[key] = instruction[key];
            if (key == 'orderBalance' && instruction[key]) {
                // 金额单位为万元
                this.orderForm.orderBalance = instruction.orderBalance / 10000;
            }
        }
    }

    // 获取资产单元编码下拉数据
    get computedAssetCodeSelectData(): any {
        let data = uniqueFunc(this.fundAccountCodeSelectData[this.orderForm.fundCode], 'assetCode');
        return data;
    }

    // 获取组合编码下拉框数据
    get computedFundAccountCodeSelectData() {
        let data = this.fundAccountCodeSelectData[this.orderForm.fundCode];
        let selectData = [];
        if (data && this.SHOW_SECURITY) {
            const obj = data.filter(item => item.assetCode == this.orderForm.assetCode);
            selectData = obj || [];
        } else {
            selectData = data;
        }
        return selectData;
    }

    /**
     * 查询证券代码下拉
     */
    queryStockCodeList(value: string) {
        getEtfList(value).then(res => {
            this.stockCodeSelectData = res;
        });
    }

    /**
     * 表单字段变化事件
     * @param value 字段值
     * @param field 字段名
     */
    async handleFormChange(value: string, field: string) {
        if (field === 'stockCode') {
            this.handleStockCodeChange(value);
        } else if (field === 'fundCode') {
            this.handleFundCodeChange(value);
            this.handleCalcAmountOrBalance();
        }
        if (['orderDirection', 'orderAmount', 'orderBalance', 'targetType'].includes(field)) {
            // 更新成分股表格计算状态
            this.$emit('handleRefreshTableState');
            this.handleCalcAmountOrBalance();
        }
        this.$emit('getOrderForm', this.orderForm, 15);
    }

    // 产品下拉组件--子组件事件传
    getFundCode(val: any) {
        if (this.orderForm.fundCode == val) {
            return;
        }
        this.orderForm.fundCode = val;
        this.handleFormChange(val, 'fundCode');
    }

    // 数字输入框组件--子组件事件传递
    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.orderForm[field] = value;
        this.handleFormChange(value, field);
    }

    /**
     * 产品代码变化事件
     * @param fundCode 当前选中的产品代码
     */
    handleFundCodeChange(fundCode: string) {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === fundCode) || {};
        this.orderForm.fundNameSt = fund?.fundNameSt;
        // 选中产品时资产单元编码默认选中第一项
        if (this.computedAssetCodeSelectData?.length) {
            this.orderForm.assetCode = this.computedAssetCodeSelectData[0].assetCode;
            this.orderForm.assetName = this.computedAssetCodeSelectData[0].assetName;
        } else {
            this.orderForm.assetCode = '';
            this.orderForm.assetName = '';
        }
        // 选中产品时组合编码默认选中第一项
        if (this.computedFundAccountCodeSelectData?.length) {
            this.orderForm.fundAccountCode = this.computedFundAccountCodeSelectData[0].fundAccountCode;
            this.orderForm.fundAccountName = this.computedFundAccountCodeSelectData[0].fundAccountName;
        } else {
            this.orderForm.fundAccountCode = '';
            this.orderForm.fundAccountName = '';
        }
    }

    /**
     * 证券代码下拉选项点击事件
     */
    handleLabelClick(label: string) {
        this.orderForm.stockName = label;
    }

    /**
     * 证券代码变化事件
     * @param stockCode 当前选中的证券代码
     */
    handleStockCodeChange(stockCode: string) {
        // 判断 ETF成分股不是最新日期，不允许下达！ 给提示
        this.etfBasicInfo = null;
        this.orderForm.orderAmount = '';
        this.orderForm.orderBalance = '';
        this.orderForm.stockName = '';
        if (stockCode) {
            getETFBasicInfo(stockCode).then(res => {
                if (res && res.length) {
                    this.etfBasicInfo = res[0];
                } else {
                    this.etfBasicInfo = null;
                }
                let nowDate = moment().format('YYYYMMDD');
                if (String(this.etfBasicInfo?.fileDate || 0) !== nowDate) {
                    this.yh_message_warn('ETF成分股不是最新日期，不允许下达！');
                }
                if (this.showIcon) {
                    // 父组件为风险试算页面
                    this.$emit('getETFBasicInfo', this.etfBasicInfo, '15');
                } else {
                    // 父组件为ETF指令页面
                    this.$emit('getETFBasicInfo', this.etfBasicInfo);
                }
            });
        }
    }

    /**
     * 计算指令数量或金额
     */
    async handleCalcAmountOrBalance() {
        let form = {
            estimatecash: this.etfBasicInfo?.estimatecash || 0,
            execType: this.etfBasicInfo?.execType || '',
            fundCode: this.orderForm.fundCode || '',
            instructionAmount: Number(this.orderForm.orderAmount || 0) || 0,
            instructionBalance: Number(this.orderForm.orderBalance || 0) * 10000 || 0,
            orderDirection: this.orderForm.orderDirection || '',
            stockCode: this.orderForm.stockCode || '',
            stockTargetType: this.orderForm.targetType == '1' ? '2' : '1',
        };

        if (this.orderForm.stockCode) {
            // 选了证券 传参给接口获取指令数量和金额
            await getInstInfo(form).then(res => {
                if (this.orderForm.targetType == '1') {
                    if (res?.instructionBalance) {
                        // 单位万元
                        this.orderForm.orderBalance = res?.instructionBalance / 10000;
                    } else {
                        this.orderForm.orderBalance = 0;
                    }
                } else {
                    this.orderForm.orderAmount = res?.instructionAmount || 0;
                }
                this.$emit('getOrderForm', this.orderForm, 15);
            });
        }
    }

    /**
     * 关闭成分股信息对话框
     */
    closeStockDialog() {
        this.stockDialog = false;
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/order-form';
.icon-form-item {
    position: relative;
    .el-icon-warning-outline {
        font-size: 22px;
        font-weight: 500;
        color: #409eff;
        cursor: pointer;
        position: absolute;
        right: -25px;
        top: 5px;
    }
}
</style>
